package com.ztc.util;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * 文本工具.
 */
public class TextUtils extends StringUtils {
    private static final String REGEX = "(?<=(\\{\\{))([\\S\\s]*?)(?=(\\}\\}))";
    private static final String IS_NUMBER = "(^-?[1-9]\\d*$)|(^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$)";

    /**
     * 将模板格式化
     *
     * @param str   模板
     * @param param 数据
     * @return
     */
    public static String templet(String str, Map<String, Object> param) {
        Pattern pattern = Pattern.compile(REGEX, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            str = str.replaceAll("\\{\\{" + matcher.group() + "\\}\\}", getValue(matcher.group(), param));
        }
        return str;
    }

    /**
     * 生成随机 bits 位的纯数字
     *
     * @param bits
     * @return
     */
    public static String random(int bits) {
        return String.valueOf(Math.random()).substring(2, 2 + bits);
    }

    public static boolean isNumber(String str) {
        return test(IS_NUMBER, str);
    }

    /**
     * 生成随机 字符串
     *
     * @param length 表示生成字符串的长度
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 正则式校验
     *
     * @param regex 正则式
     * @param str   待校验字符串
     * @return
     */
    public static boolean test(String regex, String str) {
        if (isEmpty(regex) || isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str.trim());
        return matcher.matches();
    }

    private static String getValue(String key, Map<String, Object> param) {
        if (key == null || param == null) {
            return "";
        }
        Object obj = param.get(key);
        if (obj == null) {
            return "";
        } else if (obj instanceof String) {
            return (String) obj;
        } else if (obj.getClass().isArray()) {
            return join((Object[]) obj, ",");
        } else if (obj instanceof List) {
            return join((List<?>) obj, ",");
        } else {
            return String.valueOf(obj);
        }
    }
}
